package com.user.handler;

import com.common.exception.users.UsersException;
import com.common.handler.RedisKeysHandler;
import com.user.domain.pojo.User;
import com.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service(value = "phone-code-login")
@RequiredArgsConstructor
public class PhoneCodeHandler implements LoginHandler{
    private final StringRedisTemplate stringRedisTemplate;
    private final UserMapper userMapper;
    private final UserDetailsService userDetailsService;

    @Override
    public UserDetails login(Object principal, Object credentials) {
        String phone = (String) principal;
        String code = (String) credentials;
        // 获取用户输入的验证码
        String originCode = stringRedisTemplate.opsForValue().get(RedisKeysHandler.getLoginPhoneCodeKey(phone));
        if (originCode == null){
            // 表示验证码已经过期
            throw new BadCredentialsException("验证码已经失效请重试") {
            };
        }
        if (!Objects.equals(code, originCode)){
            // 验证码错误
            throw new BadCredentialsException("验证码错误，请重试");
        }
        // 清空验证码存储
        stringRedisTemplate.delete(RedisKeysHandler.getLoginPhoneCodeKey(phone));
        User users = userMapper.querySelectByPhone(phone);
        if (users == null){
            throw new UsersException("用户不存在，请先注册");
        }
        return userDetailsService.loadUserByUsername(users.getUsername());
    }
}
